﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UnityMultiPlayerGameServer.Clients;
using UnityMultiPlayerGameServer.Manager;

namespace UnityMultiPlayerGameServer
{
    internal class Server
    {
        private Socket socket;

        /// <summary>
        /// 启动Socket
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <param name="port">端口号</param>
        /// <param name="count">监听数量</param>
        public void Start(string ip, int port, int count)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            try
            {
                socket.Bind(ipEndPoint);
                socket.Listen(count);

                socket.BeginAccept(AcceptCallback, null);
                Console.WriteLine("TCP started: " + ip + " " + port);
            }
            catch (Exception e)
            {
                Console.WriteLine("初始化TCP时出错: " + e.ToString());
                throw;
            }

        }

        private void AcceptCallback(IAsyncResult iar)
        {
            try
            {
                Socket clientSocket = socket.EndAccept(iar);
                Client client = new Client(clientSocket);

                ClientManager.Instance.AddClientList(client);

                socket.BeginAccept(AcceptCallback, null);
            }
            catch (Exception e)
            {               
                Console.WriteLine("服务器接收客户端时出错: " + e.Message);
                //接收出错时直接进行下一次接收，这次不管
                socket.BeginAccept(AcceptCallback, null);
            }
            
        }

    }
}
